package com.itheima.health.controller;


import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Member;
import com.itheima.health.pojo.Order;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.OrderService;
import com.itheima.health.service.SetMealService;
import com.itheima.health.vo.OrderSubmitParam;
import lombok.extern.slf4j.Slf4j;
import org.junit.Rule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RequestMapping("/mobile/order")
@RestController
public class MobileOrderController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MemberService memberService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private SetMealService setMealService;
    /**
     * 提交预约信息
     */
    @RequestMapping("/submit")
    public Result submit(@RequestBody OrderSubmitParam param){
        log.info("[提交预约信息]data：{}", param);
        //先获取验证码
        String  validateCode = param.getValidateCode();
        String redisKey = RedisConst.VALIDATE_CODE_PREFIX +"_ORDER_"+param.getTelephone();
        //从redis 获取  验证码
        String code = redisTemplate.opsForValue().get(redisKey).toString();
        if (!StringUtils.isEmpty(code)&& code.equals(validateCode)){
            // 创建会员或更新信息
            Member member = new Member();
            member.setIdCard(param.getIdCard());
            member.setPhoneNumber(param.getTelephone());
            member.setName(param.getName());
            member.setSex(param.getSex());
            member = memberService.createOrUpdate(member);

            //提交预约信息
            Order order = new Order();
            order.setOrderStatus(Order.ORDERSTATUS_NO);//设置预约到诊状态
            order.setSetmealId(param.getSetMealId());//套餐id
            order.setOrderType(Order.ORDERTYPE_WEIXIN);//设置预约的方式
            order.setOrderDate(param.getOrderDate());//设置预约时间
            order.setMemberId(member.getId());//设置会员id
            order = orderService.add(order);
            return new Result(true, MessageConst.ORDER_SUCCESS,order);
        }else {
            return new Result(false,MessageConst.GET_ORDERSETTING_FAIL);
        }
    }

}
